package edu.fivegroup.mall.goods;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/allGoods")
public class AllGoodsHandler extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        GoodsDao goodsDao = new GoodsDaoImpl();

        try {
            int page = Integer.parseInt(req.getParameter("page"));
            int size = Integer.parseInt(req.getParameter("size"));
            String keyword = req.getParameter("keyword");
            if (keyword == null) keyword = ""; // 默认空关键词

            List<Goods> pageData = goodsDao.findAllGoods(page, size, keyword);
            int total = goodsDao.getTotalGoods(keyword);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("data", pageData);
            response.put("total", total);
            response.put("msg", "success");

            resp.getWriter().write(new Gson().toJson(response));
        } catch (NumberFormatException e) {
            sendError(resp, 400, "参数格式错误");
        } catch (Exception e) {
            sendError(resp, 500, "服务器内部错误");
        }

    }
    private void sendError(HttpServletResponse resp, int code, String msg) throws IOException {
        Map<String, Object> error = new HashMap<>();
        error.put("code", code);
        error.put("msg", msg);
        resp.setStatus(code);
        resp.getWriter().write(new Gson().toJson(error));
    }
}
